﻿using System;
using System.Windows.Forms;
using AfterTheDeadlineNet2Adapter;
using WindowsLive.Writer.Api;

namespace GrammarCheckerPlugin
{
    [WriterPluginAttribute(
        "383E7BB7-F9BD-4EC9-B028-9AA17D45702B", 
        "Grammar Checker",
        Description="This plugin checks your post for grammar and spell errors.",
        PublisherUrl="http://blogs.microsoft.co.il/blogs/arik",
        ImagePath = "GrammarCheckerPlugin.png"
        )]
    [InsertableContentSource("Grammar Check")]
    public class GrammarChecker : ContentSource 
    {
        private const int CharacterPadding = 50;
        private const string MessageBoxCaption = "Spelling and Grammar";

        private static IAfterTheDeadlineServiceAdapter GetGrammarCheckerService()
        {
            Type serviceType = Type.GetTypeFromProgID("AfterTheDeadlineNet2Adapter.AfterTheDeadlineServiceAdapter");

            object serviceInstance = Activator.CreateInstance(serviceType);
            IAfterTheDeadlineServiceAdapter service = (IAfterTheDeadlineServiceAdapter)serviceInstance;
            return service;
        }

        public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content)
        {
            try
            {
                string originalText = content;

                IAfterTheDeadlineServiceAdapter grammarCheckerService = GetGrammarCheckerService();

                grammarCheckerService.InitService("GrammarCheckerForWindowsLiveWriter", "GAECECGAECECGAECECGAECECGAECECGA");

                var errors = grammarCheckerService.CheckDocument(content);

                foreach (var error in errors)
                {
                    var spellingForm = new SpellingForm();

                    string helpMessage = "";
                    if (!string.IsNullOrEmpty(error.Url))
                    {
                        helpMessage = grammarCheckerService.Info(error.String);
                    }

                    string wordWithcontext = string.IsNullOrEmpty(error.Precontext) ? error.String : error.Precontext + " " + error.String;
                    int wordWithContextLocation = content.IndexOf(wordWithcontext);
                    int startIndex = Math.Max(wordWithContextLocation - CharacterPadding, 0);
                    int length = Math.Min(wordWithcontext.Length + 2 * CharacterPadding, content.Length - startIndex);

                    string currentText = string.Format("...{0}...", content.Substring(startIndex, length).Trim(' ', '\n'));
                    currentText = currentText.Replace(wordWithcontext, string.Format("<b>{0}</b>",wordWithcontext));

                    spellingForm.InitSpellingForm(error.Description, currentText, error.String, error.Suggestions, helpMessage);
                            
                    DialogResult result = spellingForm.ShowDialog(dialogOwner);

                    switch (result)
                    {
                        case DialogResult.OK:
                            // replace word
                            //string wordWithcontext = string.IsNullOrEmpty(error.Precontext) ? error.String : error.Precontext + " " + error.String;
                            string wordAfterFix = string.IsNullOrEmpty(error.Precontext) ? spellingForm.SelectedWord : error.Precontext + " " + spellingForm.SelectedWord;
                            content = content.Replace(wordWithcontext, wordAfterFix);
                            break;

                        case DialogResult.Ignore:
                            // ignore word
                            break;

                        case DialogResult.Cancel:
                            // cancel grammar check
                            content = originalText;
                            return DialogResult.OK;
                    }
                }

                MessageBox.Show(dialogOwner, "Check completed!", MessageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                string message = 
                    string.Format(
                        "{0}\n\n----------------------Exception Details----------------------\n\n{1}", 
                        "An error has occurred, try selecting a smaller text region.",
                        ex.ToString());
                
                MessageBox.Show(dialogOwner, message, MessageBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return System.Windows.Forms.DialogResult.OK;
        }
    }
}
